Popular Searches
Popular Course Categories
Popular Courses

Click and Hold

Mouse & Keyboard Actions

<div class="selenium-notes">

<h1>Click and Hold in Selenium WebDriver</h1>

<p>Click and Hold is an advanced mouse interaction used in Selenium WebDriver when the mouse button needs to remain pressed while another action is performed. It is commonly used for drag-and-drop operations, sliders, custom mouse interactions, sortable components, drawing interfaces, and other web applications that depend on continuous mouse-button interaction.</p>

<p>In Selenium Java, the <code>Actions</code> class provides the <code>clickAndHold()</code> method. The method can be combined with <code>moveToElement()</code>, <code>moveByOffset()</code>, <code>release()</code>, and <code>perform()</code> to create realistic mouse interaction sequences.</p>

<p><a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training Course</a> | <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>

<hr>

<h2>1. What is Click and Hold?</h2>

<p>Click and Hold is a mouse interaction in which the user presses the mouse button on an element and keeps the button pressed instead of immediately releasing it.</p>

<p>In Selenium, this interaction is commonly created using the <code>clickAndHold()</code> method of the <code>Actions</code> class.</p>

<pre><code>Actions actions = new Actions(driver);

actions.clickAndHold(element).perform();</code></pre>

<hr>

<h2>2. Why is Click and Hold Important?</h2>

<p>Many modern web applications require the mouse button to remain pressed while the pointer is moved or another action is performed.</p>

<ul>

<li>Supports drag-and-drop operations.</li>

<li>Supports custom mouse interactions.</li>

<li>Helps automate sliders and draggable controls.</li>

<li>Supports sortable UI components.</li>

<li>Can be used with drawing interfaces.</li>

<li>Provides greater control over mouse interactions.</li>

<li>Can be combined with other Actions methods.</li>

</ul>

<hr>

<h2>3. Actions Class</h2>

<p>The <code>Actions</code> class is Selenium's API for creating advanced keyboard and mouse interactions. It can be used for click and hold, drag and drop, hover, double click, right click, keyboard shortcuts, and other composite interactions.</p>

<pre><code>Actions actions = new Actions(driver);</code></pre>

<hr>

<h2>4. Basic Click and Hold Syntax</h2>

<pre><code>Actions actions = new Actions(driver);

actions.clickAndHold(element).perform();</code></pre>

<p>The interaction can be understood as:</p>

<pre><code>Locate Element

     ↓

Move Pointer

     ↓

Press Mouse Button

     ↓

Keep Button Pressed

     ↓

Perform Additional Action

     ↓

Release Mouse Button</code></pre>

<hr>

<h2>5. Import Required Classes</h2>

<pre><code>import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;</code></pre>

<hr>

<h2>6. Simple Click and Hold Example</h2>

<pre><code>WebDriver driver = new ChromeDriver();

 

driver.get("https://example.com");

 

WebElement element = driver.findElement(

    By.id("source")

);

 

Actions actions = new Actions(driver);

 

actions.clickAndHold(element).perform();</code></pre>

<hr>

<h2>7. Click and Hold with WebElement</h2>

<p>The simplest approach is to locate a WebElement and pass it directly to <code>clickAndHold()</code>.</p>

<pre><code>WebElement element = driver.findElement(

    By.id("draggable")

);

 

new Actions(driver)

    .clickAndHold(element)

    .perform();</code></pre>

<hr>

<h2>8. Click and Hold Without Specifying an Element</h2>

<p>The Actions API also supports <code>clickAndHold()</code> without an element. In this case, the action applies to the current mouse location.</p>

<pre><code>new Actions(driver)

    .clickAndHold()

    .perform();</code></pre>

<p>This form should be used carefully because the current pointer position must be appropriate for the intended interaction.</p>

<hr>

<h2>9. Click and Hold Followed by Move</h2>

<p>A common use case is pressing the mouse button and then moving the pointer while keeping the button pressed.</p>

<pre><code>new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .perform();</code></pre>

<hr>

<h2>10. Click and Hold Followed by Release</h2>

<p>After holding the mouse button, the <code>release()</code> method can be used to release it.</p>

<pre><code>new Actions(driver)

    .clickAndHold(source)

    .release()

    .perform();</code></pre>

<hr>

<h2>11. Complete Click and Hold Sequence</h2>

<p>A complete mouse sequence can combine movement, click and hold, movement to a destination, and release.</p>

<pre><code>new Actions(driver)

    .moveToElement(source)

    .clickAndHold()

    .moveToElement(target)

    .release()

    .perform();</code></pre>

<hr>

<h2>12. Click and Hold for Drag and Drop</h2>

<p>Click and hold is one of the fundamental operations behind manual drag-and-drop automation.</p>

<pre><code>Actions actions = new Actions(driver);

 

actions.clickAndHold(source)

       .moveToElement(target)

       .release()

       .perform();</code></pre>

<hr>

<h2>13. Click and Hold vs click()</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>click()</th><th>clickAndHold()</th></tr>

<tr><td>Mouse button</td><td>Pressed and released</td><td>Pressed and kept down</td></tr>

<tr><td>Typical use</td><td>Normal click</td><td>Drag or continuous interaction</td></tr>

<tr><td>Can combine with movement</td><td>Limited for this purpose</td><td>Yes</td></tr>

<tr><td>Useful for drag and drop</td><td>No</td><td>Yes</td></tr>

<tr><td>Release required separately</td><td>No</td><td>Usually yes</td></tr>

</table>

<hr>

<h2>14. Click and Hold vs Double Click</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Aspect</th><th>Click and Hold</th><th>Double Click</th></tr>

<tr><td>Mouse press</td><td>Held continuously</td><td>Two clicks</td></tr>

<tr><td>Method</td><td><code>clickAndHold()</code></td><td><code>doubleClick()</code></td></tr>

<tr><td>Typical use</td><td>Drag and continuous actions</td><td>Opening or selecting items</td></tr>

<tr><td>Release</td><td>Can be performed separately</td><td>Handled as part of click sequence</td></tr>

</table>

<hr>

<h2>15. Click and Hold with ID Locator</h2>

<pre><code>WebElement element = driver.findElement(

    By.id("dragSource")

);

 

new Actions(driver)

    .clickAndHold(element)

    .perform();</code></pre>

<hr>

<h2>16. Click and Hold with Name Locator</h2>

<pre><code>WebElement element = driver.findElement(

    By.name("dragSource")

);

 

new Actions(driver)

    .clickAndHold(element)

    .perform();</code></pre>

<hr>

<h2>17. Click and Hold with Class Name</h2>

<pre><code>WebElement element = driver.findElement(

    By.className("draggable")

);

 

new Actions(driver)

    .clickAndHold(element)

    .perform();</code></pre>

<hr>

<h2>18. Click and Hold with CSS Selector</h2>

<pre><code>WebElement element = driver.findElement(

    By.cssSelector(".draggable")

);

 

new Actions(driver)

    .clickAndHold(element)

    .perform();</code></pre>

<hr>

<h2>19. Click and Hold with XPath</h2>

<pre><code>WebElement element = driver.findElement(

    By.xpath("//div[@id='draggable']")

);

 

new Actions(driver)

    .clickAndHold(element)

    .perform();</code></pre>

<hr>

<h2>20. Click and Hold with Stable Locator</h2>

<p>Stable locators improve the reliability of mouse interaction tests.</p>

<pre><code>WebElement element = driver.findElement(

    By.cssSelector("[data-testid='drag-item']")

);

 

new Actions(driver)

    .clickAndHold(element)

    .perform();</code></pre>

<hr>

<h2>21. Click and Hold with moveToElement()</h2>

<p>The pointer can first be moved to the required element and then the mouse button can be held.</p>

<pre><code>new Actions(driver)

    .moveToElement(element)

    .clickAndHold()

    .perform();</code></pre>

<hr>

<h2>22. Click and Hold Followed by moveToElement()</h2>

<p>This is a common sequence for custom drag-and-drop interactions.</p>

<pre><code>new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .perform();</code></pre>

<hr>

<h2>23. Click and Hold Followed by moveByOffset()</h2>

<p>The pointer can be moved by a specified offset while the mouse button remains pressed.</p>

<pre><code>new Actions(driver)

    .clickAndHold(source)

    .moveByOffset(200, 100)

    .perform();</code></pre>

<p>Offset-based movement should be used carefully because responsive layouts can change element positions.</p>

<hr>

<h2>24. Click and Hold with Release</h2>

<pre><code>new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .release()

    .perform();</code></pre>

<p>The sequence represents a complete press, move, and release interaction.</p>

<hr>

<h2>25. Understanding release()</h2>

<p>The <code>release()</code> method releases the currently held mouse button. It is particularly important when using <code>clickAndHold()</code> for drag-and-drop or custom mouse interactions.</p>

<pre><code>actions.clickAndHold(source)

       .moveToElement(target)

       .release()

       .perform();</code></pre>

<hr>

<h2>26. Click and Hold for Dragging an Element</h2>

<pre><code>WebElement source = driver.findElement(

    By.id("source")

);

 

WebElement target = driver.findElement(

    By.id("target")

);

 

new Actions(driver)

    .moveToElement(source)

    .clickAndHold()

    .moveToElement(target)

    .release()

    .perform();</code></pre>

<hr>

<h2>27. Manual Drag and Drop Using Click and Hold</h2>

<p>Manual drag and drop can be useful when the direct <code>dragAndDrop()</code> method does not behave as expected with a custom component.</p>

<pre><code>Actions actions = new Actions(driver);

 

actions.moveToElement(source)

       .clickAndHold()

       .moveToElement(target)

       .release()

       .perform();</code></pre>

<hr>

<h2>28. Click and Hold for Sortable Lists</h2>

<p>Sortable lists often require an item to remain selected while it is moved to another position.</p>

<pre><code>WebElement firstItem = driver.findElement(

    By.cssSelector(".sortable-item:nth-child(1)")

);

 

WebElement secondItem = driver.findElement(

    By.cssSelector(".sortable-item:nth-child(2)")

);

 

new Actions(driver)

    .clickAndHold(firstItem)

    .moveToElement(secondItem)

    .release()

    .perform();</code></pre>

<hr>

<h2>29. Click and Hold in a Kanban Board</h2>

<p>Kanban boards use drag interactions to move tasks between columns.</p>

<pre><code>WebElement task = driver.findElement(

    By.cssSelector(".task-card")

);

 

WebElement inProgress = driver.findElement(

    By.id("inProgress")

);

 

new Actions(driver)

    .clickAndHold(task)

    .moveToElement(inProgress)

    .release()

    .perform();</code></pre>

<hr>

<h2>30. Click and Hold in a Shopping Cart</h2>

<p>An e-commerce interface may allow a product to be dragged into a shopping cart.</p>

<pre><code>WebElement product = driver.findElement(

    By.cssSelector(".product-card")

);

 

WebElement cart = driver.findElement(

    By.id("cart")

);

 

new Actions(driver)

    .clickAndHold(product)

    .moveToElement(cart)

    .release()

    .perform();</code></pre>

<hr>

<h2>31. Click and Hold for a Slider</h2>

<p>Some sliders require the user to press and hold the slider handle while moving it horizontally or vertically.</p>

<pre><code>WebElement slider = driver.findElement(

    By.id("priceSlider")

);

 

new Actions(driver)

    .clickAndHold(slider)

    .moveByOffset(100, 0)

    .release()

    .perform();</code></pre>

<hr>

<h2>32. Horizontal Slider Example</h2>

<pre><code>WebElement sliderHandle = driver.findElement(

    By.cssSelector(".slider-handle")

);

 

new Actions(driver)

    .clickAndHold(sliderHandle)

    .moveByOffset(150, 0)

    .release()

    .perform();</code></pre>

<hr>

<h2>33. Vertical Slider Example</h2>

<pre><code>WebElement sliderHandle = driver.findElement(

    By.cssSelector(".vertical-slider-handle")

);

 

new Actions(driver)

    .clickAndHold(sliderHandle)

    .moveByOffset(0, 100)

    .release()

    .perform();</code></pre>

<hr>

<h2>34. Click and Hold with Target Offset</h2>

<p>Some custom components respond only when the pointer is released at a specific location inside the target.</p>

<pre><code>new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target, 20, 20)

    .release()

    .perform();</code></pre>

<hr>

<h2>35. Click and Hold with Intermediate Movement</h2>

<p>Complex applications may require the pointer to move through an intermediate location before reaching the final destination.</p>

<pre><code>new Actions(driver)

    .moveToElement(source)

    .clickAndHold()

    .moveByOffset(100, 0)

    .moveToElement(target)

    .release()

    .perform();</code></pre>

<hr>

<h2>36. Click and Hold with Pause</h2>

<p>A pause can be inserted into an Actions sequence when the application requires a short interval during the interaction.</p>

<pre><code>new Actions(driver)

    .moveToElement(source)

    .clickAndHold()

    .pause(Duration.ofMillis(500))

    .moveToElement(target)

    .release()

    .perform();</code></pre>

<hr>

<h2>37. Required Duration Import</h2>

<pre><code>import java.time.Duration;</code></pre>

<hr>

<h2>38. Why Use Pause Carefully?</h2>

<p>Pause can help with specific UI behaviors, but it should not be used as a replacement for proper synchronization. Prefer condition-based explicit waits whenever the application exposes a state that can be waited for.</p>

<hr>

<h2>39. Click and Hold with Explicit Wait</h2>

<p>Dynamic web applications may load the element after the initial page load. Explicit waits can help synchronize the test before starting the interaction.</p>

<pre><code>WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement source = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("source")

    )

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();</code></pre>

<hr>

<h2>40. Explicit Wait Imports</h2>

<pre><code>import java.time.Duration;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;</code></pre>

<hr>

<h2>41. Click and Hold on Dynamic Elements</h2>

<p>When the DOM changes dynamically, locate the element after the required application state has been reached.</p>

<pre><code>WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement source = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.cssSelector(".dynamic-source")

    )

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();</code></pre>

<hr>

<h2>42. Avoid Thread.sleep()</h2>

<p>Hard-coded delays can make tests unnecessarily slow and may still fail if the application takes longer than the selected delay.</p>

<pre><code>Thread.sleep(3000);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();</code></pre>

<p>Prefer explicit waits that synchronize with an actual UI condition.</p>

<hr>

<h2>43. Click and Hold with Visibility Check</h2>

<pre><code>WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement source = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("source")

    )

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();</code></pre>

<hr>

<h2>44. Click and Hold with Element Clickability</h2>

<pre><code>WebElement source = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

).until(

    ExpectedConditions.elementToBeClickable(

        By.id("source")

    )

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();</code></pre>

<hr>

<h2>45. Click and Hold Inside an iframe</h2>

<p>If the element exists inside an iframe, Selenium must switch into that iframe before interacting with the element.</p>

<pre><code>driver.switchTo().frame("dragFrame");

 

WebElement source = driver.findElement(

    By.id("source")

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();

 

driver.switchTo().defaultContent();</code></pre>

<hr>

<h2>46. Click and Hold in Nested Frames</h2>

<pre><code>driver.switchTo().frame("outerFrame");

driver.switchTo().frame("innerFrame");

 

WebElement source = driver.findElement(

    By.id("source")

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();

 

driver.switchTo().defaultContent();</code></pre>

<hr>

<h2>47. Click and Hold with Scrolling</h2>

<p>If the required element is outside the visible viewport, it may be useful to scroll it into view before performing the mouse interaction.</p>

<pre><code>WebElement source = driver.findElement(

    By.id("source")

);

 

((JavascriptExecutor) driver).executeScript(

    "arguments[0].scrollIntoView({block:'center'});",

    source

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();</code></pre>

<hr>

<h2>48. JavaScript Executor Import</h2>

<pre><code>import org.openqa.selenium.JavascriptExecutor;</code></pre>

<hr>

<h2>49. Click and Hold on Responsive Applications</h2>

<p>Responsive layouts can change element positions and dimensions. Element-based interactions are generally more maintainable than hard-coded screen coordinates.</p>

<pre><code>WebElement source = driver.findElement(

    By.cssSelector(".responsive-source")

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();</code></pre>

<hr>

<h2>50. Click and Hold with Custom UI Components</h2>

<p>Modern applications may implement draggable components using JavaScript frameworks. The exact event handling determines whether Selenium's native Actions sequence works correctly.</p>

<pre><code>WebElement source = driver.findElement(

    By.cssSelector(".custom-draggable")

);

 

WebElement target = driver.findElement(

    By.cssSelector(".custom-target")

);

 

new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .release()

    .perform();</code></pre>

<hr>

<h2>51. Click and Hold and HTML5 Drag Behavior</h2>

<p>HTML5 drag-and-drop components may use browser drag events such as <code>dragstart</code>, <code>dragover</code>, and <code>drop</code>. A normal pointer sequence may not always produce the exact application behavior expected by a custom implementation.</p>

<pre><code>&lt;div id="source" draggable="true"&gt;

    Drag Me

&lt;/div&gt;

 

&lt;div id="target"&gt;

    Drop Here

&lt;/div&gt;</code></pre>

<hr>

<h2>52. Troubleshooting Click and Hold</h2>

<p>If the interaction does not work as expected, inspect the application's DOM and event behavior before changing the automation approach.</p>

<ul>

<li>Verify the source locator.</li>

<li>Check whether the element is visible.</li>

<li>Check whether an overlay is covering the element.</li>

<li>Verify that the element is enabled.</li>

<li>Confirm that the correct iframe is selected.</li>

<li>Check whether the application requires scrolling.</li>

<li>Try a complete move and release sequence.</li>

<li>Validate the application result.</li>

</ul>

<hr>

<h2>53. Click and Hold with dragAndDrop()</h2>

<p>The direct <code>dragAndDrop()</code> method can be used when a complete source-to-target drag operation is required.</p>

<pre><code>new Actions(driver)

    .dragAndDrop(source, target)

    .perform();</code></pre>

<p>Manual <code>clickAndHold()</code> is useful when more control over the interaction sequence is required.</p>

<hr>

<h2>54. Direct Drag and Drop vs Click and Hold</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Aspect</th><th>dragAndDrop()</th><th>clickAndHold()</th></tr>

<tr><td>Purpose</td><td>Complete drag-and-drop operation</td><td>Press and maintain mouse button</td></tr>

<tr><td>Control</td><td>Less granular control</td><td>More granular control</td></tr>

<tr><td>Movement</td><td>Built into operation</td><td>Can be customized</td></tr>

<tr><td>Release</td><td>Included in complete operation</td><td>Can be performed separately</td></tr>

<tr><td>Use case</td><td>Standard drag and drop</td><td>Custom mouse sequences</td></tr>

</table>

<hr>

<h2>55. Click and Hold for Mouse-Based Workflows</h2>

<p>Click and hold can be useful when a workflow requires the user to press a control and maintain the press while another UI state changes.</p>

<ul>

<li>Drag handles.</li>

<li>Sliders.</li>

<li>Sortable lists.</li>

<li>Kanban cards.</li>

<li>Dashboard widgets.</li>

<li>Custom graphical controls.</li>

</ul>

<hr>

<h2>56. Click and Hold for Dashboard Widgets</h2>

<pre><code>WebElement widget = driver.findElement(

    By.id("salesWidget")

);

 

WebElement targetArea = driver.findElement(

    By.id("dashboardArea")

);

 

new Actions(driver)

    .clickAndHold(widget)

    .moveToElement(targetArea)

    .release()

    .perform();</code></pre>

<hr>

<h2>57. Click and Hold for File Manager</h2>

<p>A web-based file manager may allow a user to select and move a file while holding the mouse button.</p>

<pre><code>WebElement file = driver.findElement(

    By.cssSelector(".file-item")

);

 

WebElement folder = driver.findElement(

    By.cssSelector(".destination-folder")

);

 

new Actions(driver)

    .clickAndHold(file)

    .moveToElement(folder)

    .release()

    .perform();</code></pre>

<hr>

<h2>58. Click and Hold for Calendar Scheduling</h2>

<p>Some scheduling interfaces allow users to move appointments by dragging them across a calendar.</p>

<pre><code>WebElement appointment = driver.findElement(

    By.cssSelector(".appointment")

);

 

WebElement timeSlot = driver.findElement(

    By.cssSelector(".time-slot-14")

);

 

new Actions(driver)

    .clickAndHold(appointment)

    .moveToElement(timeSlot)

    .release()

    .perform();</code></pre>

<hr>

<h2>59. Click and Hold for Task Management</h2>

<pre><code>WebElement task = driver.findElement(

    By.cssSelector(".task-card")

);

 

WebElement completed = driver.findElement(

    By.id("completed")

);

 

new Actions(driver)

    .clickAndHold(task)

    .moveToElement(completed)

    .release()

    .perform();</code></pre>

<hr>

<h2>60. Click and Hold for E-Commerce Sorting</h2>

<pre><code>WebElement product = driver.findElement(

    By.cssSelector(".product-item")

);

 

WebElement destination = driver.findElement(

    By.cssSelector(".comparison-area")

);

 

new Actions(driver)

    .clickAndHold(product)

    .moveToElement(destination)

    .release()

    .perform();</code></pre>

<hr>

<h2>61. Click and Hold with Assertions</h2>

<p>The test should validate the result of the interaction instead of only checking whether Selenium executed the Actions sequence.</p>

<pre><code>new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .release()

    .perform();

 

WebElement result = driver.findElement(

    By.id("successMessage")

);

 

Assert.assertTrue(

    result.isDisplayed(),

    "Expected result was not displayed"

);</code></pre>

<hr>

<h2>62. Click and Hold with Text Validation</h2>

<pre><code>new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .release()

    .perform();

 

WebElement message = driver.findElement(

    By.id("message")

);

 

Assert.assertEquals(

    message.getText(),

    "Item moved successfully"

);</code></pre>

<hr>

<h2>63. Click and Hold with Visibility Validation</h2>

<pre><code>new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .release()

    .perform();

 

WebElement resultPanel = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

).until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("resultPanel")

    )

);

 

Assert.assertTrue(resultPanel.isDisplayed());</code></pre>

<hr>

<h2>64. Click and Hold with TestNG</h2>

<pre><code>@Test

public void verifyClickAndHoldInteraction() {

 

    WebElement source = driver.findElement(

        By.id("source")

    );

 

    WebElement target = driver.findElement(

        By.id("target")

    );

 

    new Actions(driver)

        .clickAndHold(source)

        .moveToElement(target)

        .release()

        .perform();

 

    Assert.assertTrue(

        driver.findElement(By.id("result")).isDisplayed()

    );

}</code></pre>

<hr>

<h2>65. TestNG Imports</h2>

<pre><code>import org.testng.Assert;

import org.testng.annotations.Test;</code></pre>

<hr>

<h2>66. Click and Hold in Page Object Model</h2>

<p>In the Page Object Model, the mouse interaction can be encapsulated inside a page class so that tests remain readable and reusable.</p>

<pre><code>public void moveItemToTarget() {

 

    WebElement source = driver.findElement(

        By.id("source")

    );

 

    WebElement target = driver.findElement(

        By.id("target")

    );

 

    new Actions(driver)

        .clickAndHold(source)

        .moveToElement(target)

        .release()

        .perform();

}</code></pre>

<hr>

<h2>67. Page Object Model Example</h2>

<pre><code>public class KanbanPage {

 

    private WebDriver driver;

 

    private By task = By.id("task");

    private By inProgress = By.id("inProgress");

 

    public KanbanPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void moveTaskToInProgress() {

 

        WebElement source =

            driver.findElement(task);

 

        WebElement target =

            driver.findElement(inProgress);

 

        new Actions(driver)

            .clickAndHold(source)

            .moveToElement(target)

            .release()

            .perform();

    }

}</code></pre>

<hr>

<h2>68. Calling Page Object Method</h2>

<pre><code>@Test

public void moveTask() {

 

    KanbanPage page =

        new KanbanPage(driver);

 

    page.moveTaskToInProgress();

}</code></pre>

<hr>

<h2>69. Reusable Click and Hold Utility</h2>

<pre><code>public class ActionUtils {

 

    private WebDriver driver;

 

    public ActionUtils(WebDriver driver) {

        this.driver = driver;

    }

 

    public void clickAndHold(WebElement element) {

 

        new Actions(driver)

            .clickAndHold(element)

            .perform();

    }

}</code></pre>

<hr>

<h2>70. Reusable Drag Utility</h2>

<pre><code>public void clickAndHoldAndMove(

    WebElement source,

    WebElement target

) {

    new Actions(driver)

        .clickAndHold(source)

        .moveToElement(target)

        .release()

        .perform();

}</code></pre>

<hr>

<h2>71. Utility Using Locators</h2>

<pre><code>public void clickAndHoldAndMove(

    By sourceLocator,

    By targetLocator

) {

 

    WebElement source =

        driver.findElement(sourceLocator);

 

    WebElement target =

        driver.findElement(targetLocator);

 

    new Actions(driver)

        .clickAndHold(source)

        .moveToElement(target)

        .release()

        .perform();

}</code></pre>

<hr>

<h2>72. Utility with Explicit Wait</h2>

<pre><code>public void clickAndHoldAndMove(

    By sourceLocator,

    By targetLocator

) {

 

    WebDriverWait wait =

        new WebDriverWait(driver, Duration.ofSeconds(10));

 

    WebElement source = wait.until(

        ExpectedConditions.elementToBeClickable(

            sourceLocator

        )

    );

 

    WebElement target = wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            targetLocator

        )

    );

 

    new Actions(driver)

        .clickAndHold(source)

        .moveToElement(target)

        .release()

        .perform();

}</code></pre>

<hr>

<h2>73. Click and Hold Exception Handling</h2>

<p>Unexpected UI states can cause Selenium exceptions. Frameworks should capture useful information when an interaction fails.</p>

<pre><code>try {

 

    new Actions(driver)

        .clickAndHold(source)

        .moveToElement(target)

        .release()

        .perform();

 

} catch (Exception e) {

 

    System.out.println(

        "Click and hold operation failed: "

        + e.getMessage()

    );

}</code></pre>

<hr>

<h2>74. ElementNotInteractableException</h2>

<p>This exception can occur when the source element cannot currently receive the intended interaction.</p>

<ul>

<li>Element is hidden.</li>

<li>Element is disabled.</li>

<li>Element is outside the required UI state.</li>

<li>Another element covers it.</li>

<li>The page has not finished loading.</li>

</ul>

<hr>

<h2>75. ElementClickInterceptedException</h2>

<p>An overlay, popup, modal, tooltip, or another element can interfere with the mouse interaction.</p>

<ul>

<li>Wait for the overlay to disappear.</li>

<li>Verify element visibility.</li>

<li>Check the page state.</li>

<li>Scroll the element into view when appropriate.</li>

<li>Use stable locators.</li>

</ul>

<hr>

<h2>76. StaleElementReferenceException</h2>

<p>A stale element exception may occur if the DOM changes after the source element was located.</p>

<pre><code>WebElement source = wait.until(

    ExpectedConditions.refreshed(

        ExpectedConditions.elementToBeClickable(

            By.id("source")

        )

    )

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();</code></pre>

<hr>

<h2>77. MoveTargetOutOfBoundsException</h2>

<p>This exception can occur when the requested pointer movement cannot be completed within the available browser viewport or element coordinates.</p>

<p>Possible solutions include:</p>

<ul>

<li>Scroll the element into view.</li>

<li>Avoid unnecessary coordinate offsets.</li>

<li>Use element-based movement.</li>

<li>Verify responsive layout behavior.</li>

</ul>

<hr>

<h2>78. Click and Hold with Screenshot on Failure</h2>

<pre><code>try {

 

    new Actions(driver)

        .clickAndHold(source)

        .moveToElement(target)

        .release()

        .perform();

 

} catch (Exception e) {

 

    File screenshot =

        ((TakesScreenshot) driver)

        .getScreenshotAs(OutputType.FILE);

 

    System.out.println(

        "Interaction failed: " + e.getMessage()

    );

}</code></pre>

<hr>

<h2>79. Screenshot Imports</h2>

<pre><code>import java.io.File;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;</code></pre>

<hr>

<h2>80. Logging Click and Hold Actions</h2>

<p>Logging can help identify whether the failure occurred while locating, pressing, moving, or releasing the mouse.</p>

<pre><code>System.out.println("Locating source element");

 

WebElement source = driver.findElement(

    By.id("source")

);

 

System.out.println("Starting click and hold");

 

new Actions(driver)

    .clickAndHold(source)

    .perform();

 

System.out.println("Mouse button is being held");</code></pre>

<hr>

<h2>81. Click and Hold Best Practices</h2>

<ul>

<li>Use the Actions class for advanced mouse interactions.</li>

<li>Use stable source locators.</li>

<li>Use explicit waits for dynamic elements.</li>

<li>Scroll elements into view when necessary.</li>

<li>Use element-based movement instead of fixed coordinates.</li>

<li>Release the mouse button when the interaction is complete.</li>

<li>Validate the expected application state.</li>

<li>Keep reusable Actions logic inside utilities.</li>

<li>Keep page-specific locators inside page objects.</li>

<li>Capture screenshots when important interactions fail.</li>

</ul>

<hr>

<h2>82. Common Mistakes</h2>

<ul>

<li>Using <code>click()</code> instead of <code>clickAndHold()</code> for a continuous interaction.</li>

<li>Forgetting to release the mouse button.</li>

<li>Using unstable XPath expressions.</li>

<li>Ignoring dynamic page loading.</li>

<li>Not switching into an iframe.</li>

<li>Ignoring overlays and popups.</li>

<li>Using unnecessary hard-coded sleeps.</li>

<li>Relying heavily on screen coordinates.</li>

<li>Not validating the result.</li>

<li>Duplicating Actions code across multiple tests.</li>

</ul>

<hr>

<h2>83. Click and Hold vs Fixed Coordinates</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Aspect</th><th>Element-Based</th><th>Fixed Coordinates</th></tr>

<tr><td>Maintainability</td><td>Generally better</td><td>Lower</td></tr>

<tr><td>Responsive layouts</td><td>More suitable</td><td>Risky</td></tr>

<tr><td>Locator dependency</td><td>Yes</td><td>No</td></tr>

<tr><td>Layout changes</td><td>Usually more tolerant</td><td>Can break easily</td></tr>

<tr><td>Recommended usage</td><td>Preferred</td><td>Only when necessary</td></tr>

</table>

<hr>

<h2>84. Click and Hold and Responsive Testing</h2>

<p>When testing responsive applications, element positions can change across viewport sizes. Prefer locating the element and using Actions methods instead of depending on absolute screen coordinates.</p>

<pre><code>WebElement handle = driver.findElement(

    By.cssSelector(".slider-handle")

);

 

new Actions(driver)

    .clickAndHold(handle)

    .moveByOffset(100, 0)

    .release()

    .perform();</code></pre>

<hr>

<h2>85. Click and Hold in Cross-Browser Testing</h2>

<p>Advanced mouse interactions should be tested on the browsers supported by the application.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Browser</th><th>Validation</th></tr>

<tr><td>Chrome</td><td>Click and hold behavior</td></tr>

<tr><td>Firefox</td><td>Click and hold behavior</td></tr>

<tr><td>Edge</td><td>Click and hold behavior</td></tr>

</table>

<hr>

<h2>86. Click and Hold in Parallel Testing</h2>

<p>Parallel tests should use independent WebDriver instances and appropriate test data isolation. A mouse interaction performed by one browser session should not affect another session.</p>

<hr>

<h2>87. Click and Hold in Automation Framework</h2>

<p>A professional Selenium framework should separate page elements, reusable actions, waits, and test scenarios.</p>

<ul>

<li>Page classes contain page-specific locators.</li>

<li>Action utilities contain reusable mouse interactions.</li>

<li>Wait utilities contain synchronization logic.</li>

<li>Test classes contain business scenarios.</li>

<li>Reports capture execution results.</li>

</ul>

<hr>

<h2>88. Recommended Framework Structure</h2>

<pre><code>src

├── main

│   └── java

│       ├── pages

│       ├── utilities

│       ├── waits

│       └── base

└── test

    └── java

        ├── tests

        └── testdata</code></pre>

<hr>

<h2>89. Practical Test Scenario</h2>

<p>Consider a Kanban application where a tester needs to move a task from the To Do column to the In Progress column.</p>

<ol>

<li>Launch the browser.</li>

<li>Open the application.</li>

<li>Login with valid credentials.</li>

<li>Navigate to the Kanban board.</li>

<li>Locate the task.</li>

<li>Locate the In Progress column.</li>

<li>Wait until both elements are ready.</li>

<li>Click and hold the task.</li>

<li>Move the pointer to the destination column.</li>

<li>Release the mouse button.</li>

<li>Wait for the board to update.</li>

<li>Verify that the task moved successfully.</li>

</ol>

<hr>

<h2>90. Practical Kanban Example</h2>

<pre><code>WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement task = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.cssSelector("div[data-task='TASK1001']")

    )

);

 

WebElement inProgress = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("inProgress")

    )

);

 

new Actions(driver)

    .moveToElement(task)

    .clickAndHold()

    .moveToElement(inProgress)

    .release()

    .perform();

 

WebElement result = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.cssSelector("div[data-task='TASK1001']")

    )

);

 

Assert.assertTrue(

    result.isDisplayed(),

    "Task was not displayed after the interaction"

);</code></pre>

<hr>

<h2>91. Practical Slider Example</h2>

<pre><code>WebElement sliderHandle = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

).until(

    ExpectedConditions.elementToBeClickable(

        By.cssSelector(".slider-handle")

    )

);

 

new Actions(driver)

    .clickAndHold(sliderHandle)

    .moveByOffset(120, 0)

    .release()

    .perform();</code></pre>

<hr>

<h2>92. Practical Sortable List Example</h2>

<pre><code>WebElement item1 = driver.findElement(

    By.cssSelector(".sortable-item:nth-child(1)")

);

 

WebElement item3 = driver.findElement(

    By.cssSelector(".sortable-item:nth-child(3)")

);

 

new Actions(driver)

    .clickAndHold(item1)

    .moveToElement(item3)

    .release()

    .perform();</code></pre>

<hr>

<h2>93. Practical Calendar Example</h2>

<pre><code>WebElement appointment = driver.findElement(

    By.id("appointment")

);

 

WebElement newSlot = driver.findElement(

    By.cssSelector("[data-time='14:00']")

);

 

new Actions(driver)

    .clickAndHold(appointment)

    .moveToElement(newSlot)

    .release()

    .perform();</code></pre>

<hr>

<h2>94. Sample Test Case</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Test Case ID</th><th>Scenario</th><th>Expected Result</th></tr>

<tr><td>TC-CLICKHOLD-001</td><td>Hold draggable task</td><td>Mouse remains pressed during interaction</td></tr>

<tr><td>TC-CLICKHOLD-002</td><td>Move task to another column</td><td>Task is moved successfully</td></tr>

<tr><td>TC-CLICKHOLD-003</td><td>Move slider handle</td><td>Slider value changes</td></tr>

<tr><td>TC-CLICKHOLD-004</td><td>Move sortable item</td><td>Item changes position</td></tr>

<tr><td>TC-CLICKHOLD-005</td><td>Interact with dynamic element</td><td>Element is located and interaction succeeds</td></tr>

</table>

<hr>

<h2>95. Click and Hold Test Case Template</h2>

<pre><code>Test Case ID: TC-CLICKHOLD-001

Title: Verify Click and Hold Interaction

Precondition: User is logged in

Steps:

1. Navigate to the required page

2. Locate the source element

3. Wait until the element is interactable

4. Move the pointer to the element

5. Click and hold the element

6. Perform the required movement

7. Release the mouse button

8. Validate the expected result

 

Expected Result:

The application should respond correctly to

the complete click-and-hold interaction.</code></pre>

<hr>

<h2>96. Interview Question: What is Click and Hold in Selenium?</h2>

<p>Click and Hold is an advanced mouse interaction in Selenium where the mouse button is pressed on an element and remains pressed until another action, such as movement or release, is performed.</p>

<hr>

<h2>97. Interview Question: Which Class is Used for Click and Hold?</h2>

<p>The <code>org.openqa.selenium.interactions.Actions</code> class is commonly used to perform click-and-hold and other advanced mouse interactions.</p>

<hr>

<h2>98. Interview Question: What is the Syntax of clickAndHold()?</h2>

<pre><code>new Actions(driver)

    .clickAndHold(element)

    .perform();</code></pre>

<hr>

<h2>99. Interview Question: How is Click and Hold Used for Drag and Drop?</h2>

<pre><code>new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .release()

    .perform();</code></pre>

<p>The sequence presses the mouse button on the source, moves to the target while keeping the button pressed, and then releases it.</p>

<hr>

<h2>100. Interview Question: Why is release() Used?</h2>

<p>The <code>release()</code> method releases the currently held mouse button. It is commonly paired with <code>clickAndHold()</code> when creating manual drag-and-drop or other continuous mouse interactions.</p>

<hr>

<h2>101. Interview Question: Difference Between click() and clickAndHold()?</h2>

<p><code>click()</code> performs a normal click interaction, while <code>clickAndHold()</code> presses the mouse button and keeps it pressed until the interaction is released or otherwise completed.</p>

<hr>

<h2>102. Quick Revision</h2>

<ul>

<li>Click and Hold is an advanced mouse interaction.</li>

<li>It is provided through Selenium's Actions class.</li>

<li>Use <code>clickAndHold()</code> to press and maintain the mouse button.</li>

<li>Use <code>moveToElement()</code> to move while holding.</li>

<li>Use <code>moveByOffset()</code> for relative pointer movement.</li>

<li>Use <code>release()</code> to release the mouse button.</li>

<li>Use <code>perform()</code> to execute the Actions sequence.</li>

<li>Click and Hold is useful for drag and drop.</li>

<li>It is useful for sliders and sortable components.</li>

<li>Use explicit waits for dynamic elements.</li>

<li>Use stable locators.</li>

<li>Validate the application result after the interaction.</li>

</ul>

<hr>

<h2>103. Click and Hold Checklist</h2>

<ul>

<li>Source element identified correctly.</li>

<li>Stable locator used.</li>

<li>Element is visible.</li>

<li>Element is interactable.</li>

<li>Required wait implemented.</li>

<li>Required iframe handled.</li>

<li>Element is scrolled into view when necessary.</li>

<li>Actions object created.</li>

<li>Mouse button held using <code>clickAndHold()</code>.</li>

<li>Required movement performed.</li>

<li>Mouse button released.</li>

<li>Expected result validated.</li>

<li>Screenshot captured on important failures.</li>

<li>Reusable utility used where appropriate.</li>

</ul>

<hr>

<h2>104. Practical Mini Project</h2>

<p><strong>Project:</strong> Kanban Task Click and Hold Automation</p>

<p>Automate a Kanban board where a task is selected using click and hold, moved to the In Progress column, and released.</p>

<ol>

<li>Launch the browser.</li>

<li>Open the Kanban application.</li>

<li>Login with valid credentials.</li>

<li>Navigate to the board.</li>

<li>Locate the task using a stable locator.</li>

<li>Locate the In Progress column.</li>

<li>Wait for both elements.</li>

<li>Move the pointer to the task.</li>

<li>Click and hold the task.</li>

<li>Move the pointer to the destination column.</li>

<li>Release the mouse button.</li>

<li>Wait for the UI update.</li>

<li>Validate that the task appears in the destination.</li>

<li>Capture a screenshot if the test fails.</li>

<li>Generate the test report.</li>

</ol>

<pre><code>@Test

public void verifyClickAndHoldTaskMove() {

 

    WebDriverWait wait =

        new WebDriverWait(driver, Duration.ofSeconds(10));

 

    WebElement task = wait.until(

        ExpectedConditions.elementToBeClickable(

            By.cssSelector("div[data-task='TASK1001']")

        )

    );

 

    WebElement inProgress = wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("inProgress")

        )

    );

 

    new Actions(driver)

        .moveToElement(task)

        .clickAndHold()

        .moveToElement(inProgress)

        .release()

        .perform();

 

    WebElement movedTask = wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.cssSelector("div[data-task='TASK1001']")

        )

    );

 

    Assert.assertTrue(

        movedTask.isDisplayed(),

        "Task was not displayed after click and hold operation"

    );

}</code></pre>

<hr>

<h2>105. Conclusion</h2>

<p>Click and Hold is an important Selenium WebDriver mouse interaction for applications where the mouse button must remain pressed while another action is performed. The Selenium <code>Actions</code> class provides the <code>clickAndHold()</code> method for creating this type of interaction.</p>

<p>Click and Hold becomes especially useful when combined with <code>moveToElement()</code>, <code>moveByOffset()</code>, and <code>release()</code>. This combination provides greater control over custom drag-and-drop operations, sliders, sortable lists, Kanban boards, dashboards, calendar scheduling, and other interactive components.</p>

<p>Reliable automation should use stable locators, explicit waits, correct iframe handling, element-based movement, proper release of the mouse button, and assertions that verify the final application state.</p>

<p><strong>Recommended Selenium Learning Resources:</strong></p>

<p><a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training Course</a> | <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>

</div>

Previous Next
whatsapp